<!-- InviteManage.vue -->
<template>
  <div class="invite-manage">
    <!-- 顶部操作栏 -->
    <div class="filter-container">
      <el-button type="primary" icon="el-icon-plus" @click="showCreateDialog">
        生成邀请码
      </el-button>

      <!-- 搜索和筛选 -->
      <el-input
        v-model="listQuery.keyword"
        placeholder="搜索邀请码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.type"
        placeholder="类型筛选"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option label="负责人" :value="1"/>
        <el-option label="考生" :value="2"/>
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column prop="code" label="邀请码" width="180">
        <template #default="{row}">
          <el-tag>{{ row.code }}</el-tag>
          <el-button type="text" icon="el-icon-copy-document" @click="copyCode(row.code)"></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{row}">
          <el-tag :type="row.type === 1 ? 'danger' : 'success'">
            {{ row.type === 1 ? '负责人' : '考生' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用限制" width="300">
        <template #default="{row}">
          <div>{{ row.usedCount }}/{{ row.maxUses }}次</div>
          <div v-if="row.expireTime">有效期至：{{ formatTime(row.expireTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{row}">
          <el-button type="text" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 生成邀请码对话框 -->
    <el-dialog title="生成邀请码" :visible.sync="dialogVisible" width="500px" append-to-body ref="form">
      <el-form :model="form" :rules="rules" label-width="100px">
        <el-form-item label="邀请码类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">负责人邀请码</el-radio>
            <el-radio :label="2">考生邀请码</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="最大使用次数" prop="maxUses">
          <el-input-number v-model="form.maxUses" :min="1" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="过期时间">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            placeholder="不设置则永久有效"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">生成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createInvite, getInvites, deleteInvite } from '@/api/exam/invite'
import {parseTime} from "@/utils/quiz";
import Pagination from '@/components/Pagination' // 引入分页组件

export default {
  props: {
    groupId: {
      type: [Number, String], // 接受两种类型
      required: true,
      validator(value) {
        // 确保值可以转换为数字
        return !isNaN(Number(value))
      }
    }
  },
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        groupId: Number(this.groupId),
        keyword: '',
        type: undefined
      },
      invites: [],
      dialogVisible: false,
      form: {
        type: 2,
        maxUses: 10,
        expireTime: null
      },
      rules: {
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        maxUses: [
          { required: true, message: '请输入使用次数', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // this.getList()
  },

  methods: {
    async getList() {
      console.log('getList')
      this.listLoading = true
      try {
        const res = await getInvites({
          groupId: Number(this.listQuery.groupId), // 确保是数字
          pageNum: this.listQuery.page,
          pageSize: this.listQuery.limit,
          keyword: this.listQuery.keyword,
          type: this.listQuery.type
        })
        this.list = res.rows
        this.total = res.total
      } finally {
        this.listLoading = false
      }
    },

    showCreateDialog() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form?.resetFields()
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    async submitForm() {
      try {
        // await this.$refs.form.validate()
        const { data } = await createInvite({
          groupId: this.groupId,
          ...this.form
        })

        this.$message.success('邀请码生成成功')
        this.dialogVisible = false
        await this.getList()

        // 显示生成的邀请码
        this.$alert(`邀请码：${data.code}`, '生成成功', {
          confirmButtonText: '复制',
          callback: () => {
            this.copyCode(data.code)
          }
        })
      } catch (error) {
        console.error(error)
      }
    },

    async handleDelete(id) {
      try {
        await this.$confirm('确定要删除该邀请码吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await deleteInvite(id)
        this.$message.success('删除成功')
        await this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message)
        }
      }
    },

    copyCode(code) {
      navigator.clipboard.writeText(code)
      this.$message.success('已复制到剪贴板')
    },

    formatTime(time) {
      return parseTime(time, '{y}-{m}-{d} {h}:{i}')
    }
  },
  watch: {
    groupId: {
      immediate: true, // 立即执行一次
      handler(newVal) {
        if (newVal) {
          this.listQuery.groupId = newVal;
          this.getList();
        }
      }
    }
  }
}
</script>

<style scoped>
.invite-manage {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.mt-20 {
  margin-top: 20px;
}

.filter-container {
  margin-bottom: 20px;
}
.filter-item {
  margin-right: 10px;
}

.pagination-container {
  padding: 16px 0;
  text-align: right;
}
</style>
